<?php
/**
     * 用于生成excel文件的函数
     * author:walker
     * @param $data 生成excel的数据(二维数组形式)
     * @param null $savefile 生成excel的文件名(保不指定,则为当前时间戳)
     * @param null $title 生成excel的表头(一维数组形式)
     * @param string $sheetname 生成excel的sheet名称(缺省为sheet1)
     */
    function exportExcel($data,$savefile=null,$title=null,$sheetname='sheet1'){
        ob_clean();
        date_default_timezone_set('PRC');
        //若没有指定文件名则为当前时间戳
        if(is_null($savefile)){
            $savefile=time();
        }
        //若指字了excel表头，则把表单追加到正文内容前面去
        if(is_array($title)){
            array_unshift($data,$title);
        }
        Vendor('Excel.PHPExcel');
        Vendor('Excel.PHPExcel.IOFactory');
        Vendor('Excel.PHPExcel.Reader.Excel5');
        $objPHPExcel = new PHPExcel();
        //Excel内容
        foreach($data as $k => $v){
            $obj=$objPHPExcel->setActiveSheetIndex(0);
            $row=$k+1;//行
            $nn=0;
            foreach($v as $vv){
               if ($nn < 26) {
				$col = chr(65 + $nn);
			} else if ($nn < 702) {
				$col = chr(64 + ($nn / 26)) .chr(65 + $nn % 26);
			} else {
				$col = chr(64 + (($nn - 26) / 676)) . chr(65 + ((($nn - 26) % 676) / 26)) .chr(65 + $nn % 26);
			}
                $obj->setCellValue($col.$row,$vv);//列,行,值
                $nn++;
            }
        }
     
        $objPHPExcel->getActiveSheet()->setTitle($sheetname);
        $objPHPExcel->setActiveSheetIndex(0);
        header("Content-Type: text/html;charset=utf-8");
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="'.$savefile.'.xls"');
        header('Cache-Control: max-age=0');
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
        exit;
    }
    
    
    
    /*
     * 汉字转拼音
     * $str 中文字符串
     * $type转换返回值   默认1：拼音，不带声调； 2：拼音带声调； 3：首字母
     */
    
     function Pinyin($str,$type=1){
        vendor('Pinyin/ChinesePinyin');
        $pinyin=  new \ChinesePinyin();
        switch ($type) {
            case 2:
                $return=$pinyin->TransformWithTone($str);
                break;
            case 3:
                $return=$pinyin->TransformUcwords($str);
                break;    
            case 1:
            default:
                $return=$pinyin->TransformWithoutTone($str);
                break;
        }
        return $return;
     }
     
     
     
     /*
      * Eland 读取成交数据图片文件
      */
     
    function getLandsImg($number){
        if(empty($number)){
            return false;
        }
        $array=array(
            array('name'=>'dk','title'=>'位置图'),
            array('name'=>'hx','title'=>'红线图'),
            array('name'=>'jmxz','title'=>'竞买须知'),
            array('name'=>'kg','title'=>'控规图'),
            array('name'=>'sj','title'=>'实景图'),
        );
        $path='./Public/uploads/eland/cj/';
        foreach($array as $key => $val){
            $url=$path.$val['name'].'/'.$number;
            $array[$key]['thumb']=  getFile($url);
            if(empty($array[$key]['thumb'])){
                unset($array[$key]);
            }
        }
        return $array;
    }
    
    /*
     * 读取目录文件
     * $dir 目标路径
     */
    function getFile($dir) {
    $fileArray=array();
    if (false != ($handle = opendir ( $dir ))) {
        $i=0;
        while ( false !== ($file = readdir ( $handle )) ) {
            //去掉"“.”、“..”以及带“.xxx”后缀的文件
            if ($file != "." && $file != ".."&&strpos($file,".")) {
                $fileArray[$i]=  substr($dir.'/'.$file,1);
                $i++;
            }
        }
        //关闭句柄
        closedir ( $handle );
    }
    return $fileArray;
}



 function msubstr($str, $start=0, $length, $charset="utf-8", $suffix=true){
    if(function_exists("mb_substr")){
            if ($suffix && strlen($str)>$length)
                return mb_substr($str, $start, $length, $charset)."...";
        else
                 return mb_substr($str, $start, $length, $charset);
    }
    elseif(function_exists('iconv_substr')) {
            if ($suffix && strlen($str)>$length)
                return iconv_substr($str,$start,$length,$charset)."...";
        else
                return iconv_substr($str,$start,$length,$charset);
    }
    $re['utf-8']   = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
    $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
    $re['gbk']    = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
    $re['big5']   = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
    preg_match_all($re[$charset], $str, $match);
    $slice = join("",array_slice($match[0], $start, $length));
    if($suffix) return $slice."…";
    return $slice;
}


/*自动缩略图
  */

function smallImg($url,$width,$height){
    $file=pathinfo($url);
    $small=$file['dirname'].'/s_'.$width.'_'.$height.'_'.$file['basename'];
    if(!file_exists($small)){
            $imgObj=new Think\Image();
            $imgObj->open($url);// 按照原图的比例生成一个最大为150*150的缩略图并保存为thumb.jpg
            $imgObj->thumb($width, $height)->save($small);
    }
    $head=  substr($small, 0, 9);
    if($head === './Public/'){
        $small=  substr($small, 1);
    }
    return $small;       
}


/*
 * 图片剪裁
 */

function clippingImg($url,$w,$h,$x,$y){
    $file=pathinfo($url);
    $small=$file['dirname'].'/j_'.round($w).'_'.round($h).'_'.$file['basename'];
    if(!file_exists($small)){
            $imgObj=new Think\Image();
            $imgObj->open($url);// 按照原图的比例生成一个最大为150*150的缩略图并保存为thumb.jpg
            $imgObj->crop($w,$h,$x,$y)->save($small);
    }
    $head=  substr($small, 0, 9);
    if($head === './Public/'){
        $small=  substr($small, 1);
    }
    return $small;       
}




function checkAccess(){
    $id=I('get.id');
    $cid=M('project')->where(array('id'=>$id))->getField('cid');
//    if($cid === $_SESSION['userInfo']['own']){
//        redirect('http://www.baidu.com');
//    }
}

/*
* 判断PC or  APP
 * true  APP
 * false PC
*/
function PcOrApp(){
    if(stristr($_SERVER['HTTP_VIA'],"wap")){// 先检查是否为wap代理，准确度高
            return true;
    }elseif(strpos(strtoupper($_SERVER['HTTP_ACCEPT']),"VND.WAP.WML") > 0){// 检查浏览器是否接受 WML.
            return true;
    }elseif(preg_match('/(blackberry|configuration\/cldc|hp |hp-|htc |htc_|htc-|iemobile|kindle|midp|mmp|motorola|mobile|nokia|opera mini|opera |Googlebot-Mobile|YahooSeeker\/M1A1-R2D2|android|iphone|ipod|mobi|palm|palmos|pocket|portalmmm|ppc;|smartphone|sonyericsson|sqh|spv|symbian|treo|up.browser|up.link|vodafone|windows ce|xda |xda_)/i', $_SERVER['HTTP_USER_AGENT'])){//检查USER_AGENT
            return true;	
    }else{
            return false;
    }
}


////////////////////////////以下为短信发送函数
/**
     * 模拟post进行url请求
     * @param string $url
     * @param array $post_data
     */
function request_post($url = '', $post_data = array()) {
    if (empty($url) || empty($post_data)) {
        return false;
    }
    
    $o = "";
    foreach ( $post_data as $k => $v ) 
    { 
        $o.= "$k=" . urlencode( $v ). "&" ;
    }
    $post_data = substr($o,0,-1);

    $postUrl = $url;
    $curlPost = $post_data;
    $ch = curl_init();//初始化curl
    curl_setopt($ch, CURLOPT_URL,$postUrl);//抓取指定网页
    curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
    curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
    curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
    $data = curl_exec($ch);//运行curl
    curl_close($ch);
    
    return $data;
}


// XML格式转数组格式
function xml_to_array( $xml ) { 
    $reg = "/<(\w+)[^>]*>([\\x00-\\xFF]*)<\\/\\1>/"; 
    if(preg_match_all($reg, $xml, $matches)) { 
        $count = count($matches[0]); 
        for($i = 0; $i < $count; $i++) { 
            $subxml= $matches[2][$i]; 
            $key = $matches[1][$i]; 
            if(preg_match( $reg, $subxml )) { 
                $arr[$key] = xml_to_array( $subxml ); 
            } else {
                $arr[$key] = $subxml; 
            } 
        } 
    } 
    return $arr; 
} 

// 页面显示数组格式，用于调试
function echo_xmlarr($res) {
    $res = xml_to_array($res);
    echo "<pre>";
    print_r($res);
    echo "</pre>";
}